
import axios from 'axios';

// 创建 axios 实例
const apiClient = axios.create({
    baseURL: 'http://localhost:8089',
    timeout: 10000,
});

// 请求拦截器：自动携带 Token
apiClient.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem('token');
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
            console.log('✅ 已携带 Token:', config.headers.Authorization);
        } else {
            console.warn('⚠️ Token 不存在，请检查登录状态');
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 响应拦截器：统一处理错误
apiClient.interceptors.response.use(
    (response) => response,
    (error) => {
        if (error.response?.status === 401) {
            console.error('🔐 认证失败，请重新登录');
            // 可以在这里跳转到登录页，例如：
            // router.push('/login');
        }
        return Promise.reject(error);
    }
);

export const fetchInheritors = async () => {
    try {
        const response = await apiClient.get('/api/heritage');
        let data = typeof response.data === 'string' ? JSON.parse(response.data) : response.data;

        return (data || []).map(item => ({
            id: item.id,
            name: item.name,
            image: item.image ? `http://localhost:8089/images/${item.image}` : '/default-avatar.jpg',
            category: item.category,
        }));
    } catch (error) {
        console.error('请求失败:', error);
        return [];
    }
};
export const fetchInheritorById = async (id) => {
    try {
        const response = await apiClient.get(`/api/heritage/${id}`);
        const data = response.data;
        // 统一添加图片
        return {
            ...data,
            // image: data.image ? `http://localhost:8089/images/${data.image}` : '/default-avatar.jpg'
        };
    } catch (error) {
        console.error(`获取传承人详情失败:`, error.response?.data || error.message);
        throw error;
    }
};

